import datetime
from wsgiref.util import FileWrapper
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
import os
from application.album.models import Album
from django.db.models import Q


def index(request):
    return render(request, 'base.html')


class AlbumListView(ListView):
    model = Album
    template_name = 'album/album_list.html'
    context_object_name = 'album'
    paginate_by = 8  # 每页显示8个专辑

    def get_queryset(self):
        queryset = Album.objects.all()
        search_query = self.request.GET.get('q', '')
        if search_query:
            queryset = queryset.filter(
                Q(album_title__icontains=search_query) | Q(description__icontains=search_query)
            )
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['search_query'] = self.request.GET.get('q', '')
        year = datetime.datetime.now().strftime('%Y')
        context['year'] = year
        return context


class AlbumCreateView(CreateView):
    model = Album
    fields = ['album_title', 'description', 'image']
    template_name = 'album/album_create.html'
    success_url = reverse_lazy('album_list')


def album_download(request, pk):
    # 下载图片
    album = Album.objects.get(pk=pk)
    # 统计下载次数
    album.download_count += 1
    album.save()
    return download_file(album.image.path)


def download_file(file_path):
    """
    下载文件
    :param file_path:
    :return:
    """
    file_name = os.path.basename(file_path)
    response = HttpResponse(FileWrapper(open(file_path, 'rb')), content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename="%s"' % file_name
    return response


def delete_album(request, pk):
    album = Album.objects.get(pk=pk)
    album.delete()
    return redirect('album_list')